package at.irian.jsfatwork.gui.page;

import at.irian.jsfatwork.domain.Address;
import at.irian.jsfatwork.service.CustomerService;
import org.apache.myfaces.orchestra.conversation.Conversation;
import org.apache.myfaces.orchestra.conversation.annotations.ConversationRequire;
import org.apache.myfaces.orchestra.viewController.annotations.InitView;
import org.apache.myfaces.orchestra.viewController.annotations.ViewController;
import org.springframework.context.annotation.Scope;

import javax.inject.Inject;
import javax.inject.Named;

@Named("addCustomerBean")
@Scope("manual")
@ViewController(viewIds = {ViewIds.ADD_CUSTOMER_1, ViewIds.ADD_CUSTOMER_2})
@ConversationRequire(conversationNames = "addCustomerBean", entryPointViewIds = ViewIds.ADD_CUSTOMER_1,
        navigationAction = ViewIds.ADD_CUSTOMER_1)
public class AddCustomerBean extends CustomerBeanBase {

    private Address address;
    @Inject
    private CustomerService customerService;

    @InitView
    public void createCustomer() {
        if (customer == null) {
            customer = customerService.createNew();
            address = customerService.createAddress(customer);
        }
    }

    public String save() {
        customerService.save(customer);
        customerService.saveAddress(address);
        Conversation.getCurrentInstance().invalidate();
        return ViewIds.CUSTOMER_LIST;
    }

    public String cancel() {
        Conversation.getCurrentInstance().invalidate();
        return ViewIds.CUSTOMER_LIST;
    }

    public Address getAddress() {
        return address;
    }

}